/**
 * 该场景非固定长宽: ? x ?
 * 大小取决网页打开时 innerWidth 和 innerHeight
 * 
 * HTML 设置方案
 * #main
 *   div#content
 *     -> 加载 pendants
 */

import { PathView } from '../view/pathView';

function createScene(context) {
  let t = new App(context);
  global.t = t;
  let scene = new context.Scene({
    require : ['zrender'],
    init : (libs) => t.init(libs),
    destroy : () => t.destroy(),
    collectInfo : () => t.collectInfo(),
    onMessage : (key, data) => t.onMessage(key, data),
  });
  t.sendStatus = scene.sendStatus;
  return scene;
};

class App {
  constructor(context) {
    this.context = context;

    this.paths = '';
  }

  // wait for overwrite
  sendStatus() {}

  init(libs) {
    initDom();
    this.view = new PathView({
      zrender : libs.zrender,
      dom : elContent,
      context : this.context,
    });
    this.view.startTick();
  }

  destroy() {}

  collectInfo() {
    return {
      paths : this.paths,
      scale : this.view?.scale,
      origin : this.view?.originPoint,
      panel : this.view?.canvasSize,
    }
  }

  onMessage(key, value) {
    switch (key) {
      // 考虑到 paths 可能会非常长, 需要压缩
      // value = {
      //   c : string   压缩方法. null | undefined 就是无压缩
      //   v : string   数据. 如果不压缩就是 path 原文, 否则就是压缩后的 path
      // }
      case 'update': {
        const compress = value.c;
        if (compress == null) {
          if (typeof(value.v) == 'string') {
            this.paths = value.v;
          }
        } else {
          // TODO 现在没有压缩选项
          return;
        }

        this.view.setPath(this.paths);
      } return;

      // value = {
      //   scale : number   调整缩放比例
      // }
      case 'axis': {
        this.view.setAxis(value.scale, value.originX, value.originY);
        this.sendStatus();
      } return;
    }

    console.log("path_editors 收到命令: " + name, data);
  }
}

/** @type {HTMLElement} */ let elMain;
/** @type {HTMLDivElement} */ let elContent;

function initDom(width = window.innerWidth, height = window.innerHeight) {
  elMain = document.getElementById('main');

  elContent = document.createElement('div');
  elContent.id = 'content';
  elContent.style.position = 'absolute';
  elContent.style.overflow = 'hidden';
  elContent.style.left = '0px';
  elContent.style.top = '0px';
  elMain.appendChild(elContent);
  elContent.style.width = width + 'px';
  elContent.style.height = height + 'px';
}

export default createScene;
